package com.wzw.springboot.principle.autoconfig;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Wangzhiwen
 */
@Configuration
public class CustomizedConfiguration {

    @Bean
    @Primary
    public RestTemplate restTemplate() {
        ClientHttpRequestFactory clientHttpRequestFactory = clientHttpRequestFactory();
        RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory);
        restTemplate.getMessageConverters().add(new TextHtmlMessageConverter());
        return restTemplate;
    }

    @Bean
    @Primary
    public ClientHttpRequestFactory clientHttpRequestFactory() {
        SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
        clientHttpRequestFactory.setReadTimeout(10000);
        clientHttpRequestFactory.setConnectTimeout(5000);
        return clientHttpRequestFactory;
    }

    public static class TextHtmlMessageConverter extends MappingJackson2HttpMessageConverter {
        public TextHtmlMessageConverter() {
            List<MediaType> mediaTypes = new ArrayList<>(2);
            mediaTypes.add(MediaType.TEXT_HTML);
            mediaTypes.add(MediaType.TEXT_PLAIN);
            setSupportedMediaTypes(mediaTypes);
        }
    }

}
